<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/15
 * Time: 21:02
 */

namespace app\index\controller;

use app\index\model\M;

class Tixian extends Auth
{

	public $params;
	const PAYURL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
	const KEY = 'zxdzxdzxdzxdzxdzxdzxdzxdzxdzxd23'; //请修改为自己的
	const MCHID = '1492683282'; //请修改为自己的
	const RPURL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
	const APPID = 'wxc64266ff759f07b9';//请修改为自己的
	const CODEURL = 'https://open.weixin.qq.com/connect/oauth2/authorize?';
	const OPENIDURL = 'https://api.weixin.qq.com/sns/oauth2/access_token?';
	const SECRET = '1d5ff4c27f044cbeb435c2eef5c64167';//请修改为自己的

	public function _initialize()
	{
		include WEIXIN.'/Base.php';
		$this->uid = session('Auth.Uid');
		$this->model = new M();
	}

	/**
	 * @var 我的信息
	 */
	public function index()
	{
//		echo '<pre>';
		$user_data = $this->model->find('sy_user','id',$this->uid);
		if ($user_data['balance'] < $_POST['price']){
			echo "<script>alert('账户余额不足');history.back();</script>";return;
		}
		$data = [
			'openid'  => $user_data['openid'],
			'price'   => $_POST['price'] *100
		];
		$result = $this->comPay($data);
//		var_dump($result);die;
		if ($result['result_code'] == 'FAIL'){
			echo "<script>alert('提现失败,请稍后再试');history.back();</script>";return;
		}
		$edit['balance'] = $user_data['balance'] - $_POST['price'];
		$add['name'] = $user_data['username'];
		$add['price'] = $_POST['price'];
		$add['time'] = date('Y-m-d H:i:s',time());
		$res_add = $this->model->insert('sy_user_tix',$add);
		$res = $this->model->change('sy_user',$this->uid,$edit);
		return $this->redirect('/myself');
	}

	public function  comPay($data)
	{
		$this->params = [
			'mch_appid' => self::APPID,//APPid,
			'mchid'          => self::MCHID,//商户号,
			'nonce_str'          => md5(time()), //随机字符串
			'partner_trade_no'          => date('YmdHis'), //商户订单号
			'openid'          =>$data['openid'], //用户openid
			'check_name'          => 'NO_CHECK',//校验用户姓名选项 NO_CHECK：不校验真实姓名 FORCE_CHECK：强校验真实姓名
			//'re_user_name'          => '',//收款用户姓名  如果check_name设置为FORCE_CHECK，则必填用户真实姓名
			'amount'          => $data['price'],//金额 单位分
			'desc'          => '源之东方零钱提现',//付款描述
			'spbill_create_ip'          => $_SERVER['SERVER_ADDR'],//调用接口机器的ip地址
		];
		return $this->send(self::PAYURL);
	}
	public function sign()
	{
		return $this->setSign($this->params);
	}
	public function send($url)
	{
		$res = $this->sign();
		$xml = $this->ArrToXml($res);
		$returnData = $this->postData($url, $xml);
		return $this->XmlToArr($returnData);
	}

	/**
	 * 获取签名
	 * @param array $arr
	 * @return string
	 */
	public function getSign($arr){
		//去除空值
		$arr = array_filter($arr);
		if(isset($arr['sign'])){
			unset($arr['sign']);
		}
		//按照键名字典排序
		ksort($arr);
		//生成url格式的字符串
		$str = $this->arrToUrl($arr) . '&key=' . self::KEY;
		return strtoupper(md5($str));
	}
	/**
	 * 获取带签名的数组
	 * @param array $arr
	 * @return array
	 */
	public function setSign($arr){
		$arr['sign'] = $this->getSign($arr);;
		return $arr;
	}
	/**
	 * 数组转URL格式的字符串
	 * @param array $arr
	 * @return string
	 */
	public function arrToUrl($arr){
		return urldecode(http_build_query($arr));
	}

	//数组转xml
	function ArrToXml($arr)
	{
		if(!is_array($arr) || count($arr) == 0) return '';

		$xml = "<xml>";
		foreach ($arr as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}

	//Xml转数组
	function XmlToArr($xml)
	{
		if($xml == '') return '';
		libxml_disable_entity_loader(true);
		$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		return $arr;
	}
	function postData($url,$postfields){

		$ch = curl_init();
		$params[CURLOPT_URL] = $url;    //请求url地址
		$params[CURLOPT_HEADER] = false; //是否返回响应头信息
		$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
		$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
		$params[CURLOPT_POST] = true;
		$params[CURLOPT_POSTFIELDS] = $postfields;
		$params[CURLOPT_SSL_VERIFYPEER] = false;
		$params[CURLOPT_SSL_VERIFYHOST] = false;
		//以下是证书相关代码
		$params[CURLOPT_SSLCERTTYPE] = 'PEM';
		$params[CURLOPT_SSLCERT] = EXTEND_PATH.'weixin/cert/apiclient_cert.pem';
		$params[CURLOPT_SSLKEYTYPE] = 'PEM';
		$params[CURLOPT_SSLKEY] = EXTEND_PATH.'weixin/cert/apiclient_key.pem';
//		var_dump($params[CURLOPT_SSLKEY]);die;
		curl_setopt_array($ch, $params); //传入curl参数
		$content = curl_exec($ch); //执行
		curl_close($ch); //关闭连接
		return $content;
	}


}
